package com.hruiworks.campusgroup.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hruiworks.campusgroup.common.PageVO;
import com.hruiworks.campusgroup.dao.mapper.ActivityMapper;
import com.hruiworks.campusgroup.dao.mapper.GroupMapper;
import com.hruiworks.campusgroup.manager.ActivityGroupManager;
import com.hruiworks.campusgroup.manager.entity.ActivityData;
import com.hruiworks.campusgroup.manager.entity.GroupFullInfo;
import com.hruiworks.campusgroup.pojo.entity.Activity;
import com.hruiworks.campusgroup.pojo.entity.Group;
import com.hruiworks.campusgroup.pojo.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityGroupManagerImpl implements ActivityGroupManager {

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private ActivityMapper activityMapper;


    @Override
    public PageVO<GroupFullInfo> listGroupFullInfoPageSelf(Long size, Long current, Integer created, Integer time, User user) {
        List<Group> groups = groupMapper.userSelfGroupPage(size, (current-1)*size, created, time, user.getId());
        Long count = groupMapper.userSelfGroupAllCount(created, time, user.getId());


        ArrayList<GroupFullInfo> groupFullInfos = new ArrayList<>();

        // 查找对应activity
        List<Long> activityIdList = groups.stream().map(Group::getActivityId).toList();
        if (!activityIdList.isEmpty()) {
            LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Activity::getId, activityIdList);
            Map<Long, List<Activity>> map = activityMapper.selectList(queryWrapper).stream().collect(Collectors.groupingBy(Activity::getId));
            for (Group group : groups) {
                GroupFullInfo groupFullInfo = new GroupFullInfo(group, map.get(group.getActivityId()).get(0));
                groupFullInfos.add(groupFullInfo);
            }
        }

        PageVO<GroupFullInfo> groupPageVO = new PageVO<>();
        groupPageVO.setRecords(groupFullInfos);
        groupPageVO.setTotal(count);
        groupPageVO.setSize(size);
        groupPageVO.setCurrent(current);

        return groupPageVO;
    }

    @Override
    public PageVO<ActivityData> listActivityDataPageSelf(Long size, Long current,String searchValue, User user) {
        PageVO<ActivityData> activityDataPageVO = new PageVO<>();

        activityDataPageVO.setTotal(0L);
        activityDataPageVO.setSize(size);
        activityDataPageVO.setCurrent(current);
        LocalDateTime now = LocalDateTime.now();
        // 1. 先找到所有参与过的团队
        List<Group> groupHistory = groupMapper.userSelfGroupAll(user.getId());
        List<Group> groups = groupHistory.stream().filter(g -> g.getEndTime().isBefore(now)).toList();
        if (groups.isEmpty()) {
            activityDataPageVO.setRecords(Collections.emptyList());
            return activityDataPageVO;
        }
        // 2. 提取里面的活动
        Map<Long, List<Group>> activityGroup = groups.stream().collect(Collectors.groupingBy(Group::getActivityId));
        Set<Long> activityId = activityGroup.keySet();
        // 3. 分页查询活动信息
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Activity::getId, activityId);
        if (StringUtils.isNotBlank(searchValue)) {
            queryWrapper.like(Activity::getActivityName, searchValue);
        }
        Page<Activity> activityQueryPage = new Page<>(current, size);
        Page<Activity> activityPage = activityMapper.selectPage(activityQueryPage, queryWrapper);
        if (activityPage.getSize() == 0) {
            activityDataPageVO.setRecords(Collections.emptyList());
            return activityDataPageVO;
        }
        List<ActivityData> activityDataList = new ArrayList<>();
        BigDecimal hundredDecimal = new BigDecimal("100");
        // 4. 将信息整理为ActivityData
        for (Activity activity : activityPage.getRecords()) {
            ActivityData activityData = new ActivityData();

            // 只统计已经结束的活动
            List<Group> groupList = activityGroup.get(activity.getId()).stream().filter(g -> g.getEndTime().isBefore(now)).toList();
            int times = groupList.size();
            long successCount = groupList.stream().filter(g -> Objects.equals(g.getAlreadyNum(), g.getNeededNum())).count();
            BigDecimal groupSuccessRate = new BigDecimal(successCount).divide(new BigDecimal(times), 2, RoundingMode.HALF_UP);

            activityData.setActivity(activity);
            activityData.setTimes(times);
            activityData.setGroupSuccessRate(groupSuccessRate);
            activityData.setGroupSuccessRateStr(groupSuccessRate.multiply(hundredDecimal) +"%");

            activityDataList.add(activityData);
        }


        activityDataPageVO.setRecords(activityDataList);
        activityDataPageVO.setTotal(activityPage.getTotal());
        activityDataPageVO.setSize(activityPage.getSize());
        activityDataPageVO.setCurrent(activityPage.getCurrent());

        return activityDataPageVO;
    }
}
